const express = require('express')
const Result = require('../models/Result')
//const { login, findUser ,insertUser } = require('../services/user')
const userService = require('../services/user')
const { md5, decoded } = require('../utils')
const { PWD_SALT, PRIVATE_KEY, JWT_EXPIRED } = require('../utils/constant')
const { body, validationResult } = require('express-validator')
const boom = require('boom')
const jwt = require('jsonwebtoken')
const { debug } = require('../utils/constant')
const router = express.Router()
const mailer = require('../models/sendEmail')

//发送邮件
router.post("/sendEmail", function (req, res) {
  const news = req.body
  //console.log(news)
  var code=news.code
  var username=news.username
  var email = news.email;
  var subject = "德宏师范高等专科学校公开招聘系统-密码找回";//标题
  var text ="德宏师范高等专科学校公开招聘系统-密码找回";
  var html = "<p>"+username+"考生你好</p><p>你的验证码是："+code+"</p>";
  mailer.emailTo(email,subject,text,html, function (data) {
        if(data.httpCode==200){
          new Result('验证码发送邮箱成功').success(res)
        }else{
          new Result('验证码发送邮箱失败').fail(res)
        }
     })
})

router.post(
  '/login',
  [
    body('username').isString().withMessage('用户名必须为字符'),
    body('password').isString().withMessage('密码必须为数字')
  ],
  function(req, res, next) {
    const err = validationResult(req)
    if (!err.isEmpty()) {
      const [{ msg }] = err.errors
      next(boom.badRequest(msg))
    } else {
      let { username, password } = req.body
      password = md5(`${password}${PWD_SALT}`)

      userService.login(username, password).then(user => {
        if (!user || user.length === 0) {
          new Result('登录失败').fail(res)
        } else {
          const token = jwt.sign(
            { username },
            PRIVATE_KEY,
            { expiresIn: JWT_EXPIRED }
          )
          new Result({ token }, '登录成功').success(res)
        }
      })
    }
  })

router.get('/info', function(req, res) {
  const decode = decoded(req)
  if (decode && decode.username) {
    userService.findUser(decode.username).then(user => {
      if (user) {
        user.roles = [user.role]
        new Result(user, '用户信息查询成功').success(res)
      } else {
        new Result('用户信息查询失败').fail(res)
      }
    })
  } else {
    new Result('用户信息查询失败').fail(res)
  }
})


//获取用户信息列表

router.get('/UserList', function(req, res, next) {
  userService.UserList(req.query)
    .then(({ list, count, page, pageSize }) => {
      new Result({ list, count, page: +page, pageSize: +pageSize },
        '获取用户信息成功').success(res)
    }).catch(err => {
    next(boom.badImplementation(err))
  })
})
//获取系统数据
router.get('/adminInfo', function(req, res, next) {
  userService.adminInfo(req.query).then(({ admin_user, enroll, enroll_succes, enroll_error }) => {
      new Result({ admin_user, enroll, enroll_succes, enroll_error },
        '获取系统信息成功').success(res)
    }).catch(err => {
    next(boom.badImplementation(err))
  })
})
//获取报名数据
router.get('/enrollInfo', function(req, res, next) {
  userService.enrollInfo(req.query.fileName).then(({ enroll_num, enroll_succes, enroll_error }) => {
      new Result({ enroll_num, enroll_succes, enroll_error },
        '获取报名信息成功').success(res)
    }).catch(err => {
    next(boom.badImplementation(err))
  })
})
//获取招聘计划数据
router.get('/plan', function(req, res, next) {
  userService.PlanList().then((list) => {
      new Result(list,
        '获取招聘计划信息成功').success(res)
    }).catch(err => {
    next(boom.badImplementation(err))
  })
})
//获取单个
router.get('/getOneUser', function(req, res) {
  const news = req.query.fileName
  ////console.log(news)
  userService.getOneUser(news).then(News => {
      if (News) {
          new Result(News, ' 单个用户信息查询成功').success(res)
      } else {
          new Result('单个用户信息查询失败').fail(res)
      }
  })

})

//获取单个
router.get('/getOneUserPassword', function(req, res) {
  const news = JSON.parse(req.query.fileName)
  
  //let username=news.username
  //let email=news.email
  //////console.log(news.username)
  userService.getOneUserPassword(news.username,news.email).then(News => {
    //console.log(News)
      if (News.count===1) {
          new Result(News, '请修改密码').success(res)
      } else {
          new Result('用户信息不对应').fail(res)
      }
  })

})
//获取单个，用户名查询
router.get('/getOneUserName', function(req, res) {
  const news = req.query.fileName
  ////console.log(news)
  userService.getOneUserName(news).then(News => {
      if (News) {
          new Result(News, ' 单个用户信息查询成功').success(res)
      } else {
          new Result().jsonfail(res)
      }
  })

})

//修改报名信息
router.post('/updateUser', function(req, res, next) {
  ////console.log(req.body)
  const news = req.body
  userService.updateUser(news).then(() => {
      new Result('修改用户信息成功').success(res)
  }).catch(err => {
      next(boom.badImplementation(err))
  })
}
)
//删除报名信息
router.get('/deleteUser', function(req, res, next) {
const id = req.query.id
//////console.log(req)
if (!id) {
  next(boom.badRequest(new Error('参数id不能为空')))
} else {
  userService.deleteUser(id).then(() => {
      new Result('删除用户信息成功').success(res)
  }).catch(err => {
      next(boom.badImplementation(err))
  })
}
})

//添加注册信息
router.post('/createUser', function(req, res, next) {
  ////console.log(req.body)
  let d = new Date()
  const user = req.body
  let { password } = req.body
      password = md5(`${password}${PWD_SALT}`)
  user.password=password
  user.registTime=d.getTime()
  ////console.log(user.registTime)
  userService.insertUser(user).then(() => {
      new Result('注册信息成功').success(res)
  }).catch(err => {
      next(boom.badImplementation(err))
  })
}
)

//修改密码
router.post('/updatePasswordUser', function(req, res, next) {
  ////console.log(req.body)
  const user = req.body
  let { password } = req.body
  password = md5(`${password}${PWD_SALT}`)
  user.password=password
  userService.updateUser(user).then(() => {
      new Result('修改用户密码成功').success(res)
  }).catch(err => {
      next(boom.badImplementation(err))
  })
}
)
//修改找回密码
router.post('/updatePasswordUser1', function(req, res, next) {
  ////console.log(req.body)
  const user1 = req.body
  const user = req.body.username
  let password = req.body.password
  let password1 = md5(`${password}${PWD_SALT}`)
  user1.password=password1
  userService.updateUserPassword(user,user1).then(() => {
      new Result('修改用户密码成功').success(res)
  }).catch(err => {
      next(boom.badImplementation(err))
  })
}
)
module.exports = router
